package com.uchedao.seller.ui.car.publish.condition;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.JsonObject;
import com.nostra13.universalimageloader.utils.L;
import com.uchedao.seller.R;
import com.uchedao.seller.config.Api;
import com.uchedao.seller.config.GlobalInfo;
import com.uchedao.seller.db.DbHelper;
import com.uchedao.seller.http.VolleyUtil;
import com.uchedao.seller.http.entity.DictEntity;
import com.uchedao.seller.http.request.HttpRequest;
import com.uchedao.seller.http.request.VinCarRequest;
import com.uchedao.seller.http.response.ConfigDictResponse;
import com.uchedao.seller.inf.ICheckEntityListener;
import com.uchedao.seller.inf.ICheckValueListener;
import com.uchedao.seller.inf.IOnResultBack;
import com.uchedao.seller.manager.DictionaryManager;
import com.uchedao.seller.module.BaseInfo;
import com.uchedao.seller.module.Condition;
import com.uchedao.seller.module.ConfigInfo;
import com.uchedao.seller.module.Detection;
import com.uchedao.seller.module.Draft;
import com.uchedao.seller.module.VinCarInfor;
import com.uchedao.seller.ui.car.adapter.EngineManualAdapter;
import com.uchedao.seller.ui.car.adapter.EngineManualAdapter.EngineManualAdapterListener;
import com.uchedao.seller.ui.car.publish.vin.CarDbUtil;
import com.uchedao.seller.ui.carlist.CarActivity;
import com.uchedao.seller.ui.carlist.entity.CarEntity;
import com.uchedao.seller.util.CheckValueUtil;
import com.uchedao.seller.util.T;
import com.uchedao.seller.widget.loadstate.UCheDaoRelativeLayout;
import com.uchedao.seller.widget.stickylistheaders.StickyListHeadersListView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 配置及功能检测
 */
public class ConditionVFunctioniew extends UCheDaoRelativeLayout implements EngineManualAdapterListener, IOnResultBack {

    public static final int REQUEST_CAR_BRAND = 602;// 品牌
    public static final int REQUEST_CAR_SERIES = 603;// 系列
    public static final int REQUEST_CAR_MODEL = 604;// 车型

    public static final int FORM_PAINT = 401;// 漆膜厚度检测跳过去


    //    private Condition condition = GlobalInfo.draft.condition.clone();
    private Condition condition;
    //    private ResultIntArrayPics[] paint_surface;
    private VinCarInfor vinCarInfor;

    public ConditionVFunctioniew(Context context, VinCarInfor vinCarInfor) {
        super(context);
        this.vinCarInfor = vinCarInfor;
    }

    public ConditionVFunctioniew(Context context) {
        super(context);
    }

    public ConditionVFunctioniew(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ConditionVFunctioniew(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    private static boolean isOKVin = false;
    /**
     * 是否是第一次检测vin
     */
    private  boolean firstCheckVin = false;

    @Override
    public boolean save() {
        ContentValues values = new ContentValues();
        values.put(DbHelper.KEY_DRAFT_CONDITION, toJson(condition));

        int status = condition.getStatus();
        values.put(DbHelper.KEY_DRAFT_CONDITION_STATUS, status);

        // 若VIN值为空
        if (TextUtils.isEmpty(condition.config_info.vin))
            condition.config_info.vin = GlobalInfo.draft.car_vin;

        // 如果VIN值有更改
//        else if (!condition.config_info.vin.equals(GlobalInfo.draft.car_vin)) {
//            values.put(DbHelper.KEY_DRAFT_CAR_VIN, condition.config_info.vin);
//            GlobalInfo.dbHelper.updateDrafVinByInfoId(GlobalInfo.draft.info_number, GlobalInfo.draft.car_vin);
//        }


        if (isOKVin) {
            values.put(DbHelper.KEY_DRAFT_CAR_VIN, condition.config_info.vin);
            if (!condition.config_info.vin.equals(GlobalInfo.draft.car_vin)) {
                GlobalInfo.dbHelper.updateDrafVinByInfoId(GlobalInfo.draft.info_number, GlobalInfo.draft.car_vin);
            }
        } else {
//            return false;
        }


//         int status = GlobalInfo.draft.status[Draft.TYPE_CONDITION];
//         // 若原先状态为未完成，且数据已变动，则状态改变为已完成
//         if (GlobalInfo.draft.status[Draft.TYPE_CONDITION] !=
//         Draft.STATUE_FINISH) {
//         values.put(DbHelper.KEY_DRAFT_CONDITION_STATUS, Draft.STATUE_FINISH);
//         status = Draft.STATUE_FINISH;
//         }

        // 保存成功
        if (GlobalInfo.dbHelper.updateDraf(GlobalInfo.tempOwner, values)) {
            GlobalInfo.draft.condition = condition.clone();
            GlobalInfo.draft.car_vin = condition.config_info.vin;
            GlobalInfo.draft.status[Draft.TYPE_CONDITION] = status;
            L.i(toJson(GlobalInfo.draft.condition));

            // 必填项全部填写返回true
            if(condition.config_info.getStatus() == 2)
                return true;
            else
                return false;
        }

        return false;
    }

    @Override
    public boolean dataChanged() {

//        L.i(toJson(condition));
//        L.i(toJson(GlobalInfo.draft.condition));
        return !toJson(condition).equals(toJson(GlobalInfo.draft.condition));
//        return false;
    }

    @Override
    public void initView() {

        LayoutInflater.from(mContext).inflate(R.layout.view_condition_function, this);

        // ListView listView = (ListView) functionLayout
        // .findViewById(R.id.manual_list);

        StickyListHeadersListView stickListHeadersListView = (StickyListHeadersListView) findViewById(R.id.detection_listView);

        final LinearLayout baseConfigHeader = (LinearLayout) LayoutInflater.from(mContext).inflate(R.layout.base_config_header, null);
        stickListHeadersListView.addHeaderView(baseConfigHeader);

        TextView subjectName = (TextView) baseConfigHeader.findViewById(R.id.subject_tv);
        subjectName.setText(R.string.base_config_subtitle);

        // functionAdapter = new DetectionAdapter(this, getFunctionData(),
        // functionListener);
        // stickListHeadersListView.setAdapter(functionAdapter);

        EngineManualAdapter adapter = new EngineManualAdapter(mContext, getFunctionCheckData(), this);
        stickListHeadersListView.setAdapter(adapter);

        final ConfigInfo configInfo = condition.config_info;
        configInfo.vin = GlobalInfo.draft.car_vin;

        isOKVin = true;
        firstCheckVin = true;

        // 车型
        CheckValueUtil.textBtnListener(this, R.id.base_car_brand_tv,
                R.id.base_car_brand_bt, configInfo.brand_str + " " + configInfo.series_str + " " + configInfo.model_str);

        Button base_car_brand_bt = (Button) this
                .findViewById(R.id.base_car_brand_bt);
        base_car_brand_bt.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                ((Activity) mContext).startActivityForResult(new Intent(mContext, CarActivity.class), REQUEST_CAR_BRAND);
            }
        });

        // vin码
        CheckValueUtil.textEditListener(baseConfigHeader, R.id.car_test_vin_tv, R.id.car_test_vin_et, configInfo.vin,
                new ICheckValueListener() {
                    @Override
                    public void getValue(View v, String str) {
                        // VIN长度不足
                        if (str == null || str.length() < 17) {
                            isOKVin = false;
                            ((EditText) v).setError(mContext.getString(R.string.car_vin_pattern_combination_error));
//                            baseConfigHeader.findViewById(R.id.car_test_getVIN_bt).setEnabled(false);
                            return;
                        }
//                        baseConfigHeader.findViewById(R.id.car_test_getVIN_bt).setEnabled(true);
//                        configInfo.vin = str;

                        if (configInfo.vin != str) {
                            checkVIN(str);
//                            configInfo.vin = str;
                        }

                    }
                });

//        // 获取车辆信息
//        Button car_test_getVIN_bt = (Button) baseConfigHeader.findViewById(R.id.car_test_getVIN_bt);
//        // car_test_getVIN_bt.setEnabled(true);
//        car_test_getVIN_bt.setOnClickListener(new OnClickListener() {
//
//            @Override
//            public void onClick(View v) {
//
//                EditText vinET = (EditText) baseConfigHeader.findViewById(R.id.car_test_vin_et);
//
//                String vin = vinET.getText().toString();
//                // VIN长度不足
//                if (vin.length() < 17) {
//                    vinET.setError(mContext.getString(R.string.car_vin_pattern_combination_error));
//                    ToastUtil.showToastLong(R.string.car_vin_pattern_combination_error);
//                    return;
//                }
//
//                CheckVIN(vin);
//
//            }
//        });

        // 排量
        CheckValueUtil.textEditListener(this, R.id.base_displace_tv,
                R.id.base_displace_et, configInfo == null ? ""
                        : configInfo.car_engines, new ICheckValueListener() {

                    @Override
                    public void getValue(View v, String str) {
                        configInfo.car_engines = str;
                    }
                });

        // 变速箱
        CheckValueUtil.textBtnListener(this,
                R.id.base_change_speed_type_tv, R.id.base_change_speed_type_bt,
                R.array.change_speed_type_strValues, configInfo == null ? ""
                        : configInfo.trans_type, new ICheckValueListener() {

                    @Override
                    public void getValue(View v, String str) {
                        configInfo.trans_type = str;
                    }
                });
        DictionaryManager.SyncDictCallback callback = new DictionaryManager.SyncDictCallback() {
            @Override
            public void syncCompleted(ConfigDictResponse.CarDict dictEntity) {
                if(dictEntity == null)
                    return;
                CheckValueUtil.textBtnListener(ConditionVFunctioniew.this, R.id.base_change_speed_type_tv,
                        R.id.base_change_speed_type_bt, dictEntity.gearbox_type,
                        configInfo.trans_type, new ICheckEntityListener() {
                            @Override
                            public void getValue(View v, DictEntity entity) {
                                configInfo.trans_type_key = entity.key;
                                configInfo.trans_type = entity.caption;
                            }
                        });
            }
        };
        DictionaryManager.getDictInfo(mContext, callback);

        // ABS码
        CheckValueUtil.textBtnListener(baseConfigHeader, R.id.car_test_ABS_tv, R.id.car_test_ABS_bt,
                R.array.have_entries, configInfo.abs, new ICheckValueListener() {

                    @Override
                    public void getValue(View v, String str) {
                        configInfo.abs = str;
                        L.w("configInfo.abs = " + str);
                    }
                });

        // 气囊数
        CheckValueUtil.textEditListener(baseConfigHeader, R.id.car_test_airbagCount_tv, R.id.car_test_airbagCount_et,
                configInfo.airbag, new ICheckValueListener() {
                    @Override
                    public void getValue(View v, String str) {
                        configInfo.airbag = str;
                        L.w("configInfo.airbag = " + str);
                    }
                });

        // 真皮坐椅
        CheckValueUtil.textBtnListener(baseConfigHeader, R.id.car_test_leatherSeat_tv, R.id.car_test_leatherSeat_bt,
                R.array.leather_seat_strValues, configInfo.leather_seats, new ICheckValueListener() {

                    @Override
                    public void getValue(View v, String str) {
                        configInfo.leather_seats = str;
                    }
                });

        // 电动门窗
        CheckValueUtil.textBtnListener(baseConfigHeader, R.id.car_test_eCarWindow_tv, R.id.car_test_eCarWindow_bt,
                R.array.e_car_window_strValues, configInfo.electrically_window, new ICheckValueListener() {

                    @Override
                    public void getValue(View v, String str) {
                        configInfo.electrically_window = str;
                    }
                });

        // 天窗
        CheckValueUtil.textBtnListener(baseConfigHeader, R.id.car_test_skyWindow_tv, R.id.car_test_skyWindow_bt,
                R.array.sky_window_strValues, configInfo.window, new ICheckValueListener() {

                    @Override
                    public void getValue(View v, String str) {
                        configInfo.window = str;
                    }
                });

        // 导航
        CheckValueUtil.textBtnListener(baseConfigHeader, R.id.car_test_navigation_tv, R.id.car_test_navigation_bt,
                R.array.navigation_and_other_strValues, configInfo.gps_navigator, new ICheckValueListener() {

                    @Override
                    public void getValue(View v, String str) {
                        configInfo.gps_navigator = str;
                    }
                });

        // 转向助力
        CheckValueUtil.textBtnListener(baseConfigHeader, R.id.car_test_turnAroundPower_tv,
                R.id.car_test_turnAroundPower_bt, R.array.have_entries, configInfo.booster_type,
                new ICheckValueListener() {

                    @Override
                    public void getValue(View v, String str) {
                        configInfo.booster_type = str;
                    }
                });

        // 电动座椅
        CheckValueUtil.textBtnListener(baseConfigHeader, R.id.car_test_eSeat_tv, R.id.car_test_eSeat_bt,
                R.array.e_seat_strValues, configInfo.electrically_seat, new ICheckValueListener() {

                    @Override
                    public void getValue(View v, String str) {
                        configInfo.electrically_seat = str;
                    }
                });

        // 空调
        CheckValueUtil.textBtnListener(baseConfigHeader, R.id.car_test_airConditioner_tv,
                R.id.car_test_airConditioner_bt, R.array.air_conditioner_strValues, configInfo.air,
                new ICheckValueListener() {

                    @Override
                    public void getValue(View v, String str) {
                        configInfo.air = str;
                    }
                });

        // 音响
        CheckValueUtil.textBtnListener(baseConfigHeader, R.id.base_sount_sys_tv, R.id.base_sount_sys_bt,
                R.array.sound_sys_strValues, configInfo.sound_system, new ICheckValueListener() {

                    @Override
                    public void getValue(View v, String str) {
                        configInfo.sound_system = str;
                    }
                });

        // 定速巡航
        CheckValueUtil.textBtnListener(baseConfigHeader, R.id.car_test_automaticCruise_tv,
                R.id.car_test_automaticCruise_bt, R.array.navigation_and_other_strValues, configInfo.auto_adapt_drive,
                new ICheckValueListener() {

                    @Override
                    public void getValue(View v, String str) {
                        configInfo.auto_adapt_drive = str;
                    }
                });

        // 电动反光镜
        CheckValueUtil.textBtnListener(baseConfigHeader, R.id.car_test_eReflector_tv, R.id.car_test_eReflector_bt,
                R.array.e_reflector_strValues, configInfo.back_mirror_electrically, new ICheckValueListener() {

                    @Override
                    public void getValue(View v, String str) {
                        configInfo.back_mirror_electrically = str;
                    }
                });

        // 智能钥匙
        CheckValueUtil.textBtnListener(baseConfigHeader, R.id.base_smart_key_tv, R.id.base_smart_key_bt,
                R.array.have_entries, configInfo.smart_key, new ICheckValueListener() {

                    @Override
                    public void getValue(View v, String str) {
                        configInfo.smart_key = str;
                    }
                });

        // DVD
        CheckValueUtil.textBtnListener(baseConfigHeader, R.id.car_test_DVD_tv, R.id.car_test_DVD_bt,
                R.array.navigation_and_other_strValues, configInfo.dvd, new ICheckValueListener() {

                    @Override
                    public void getValue(View v, String str) {
                        configInfo.dvd = str;
                    }
                });

        // 倒车雷达
        CheckValueUtil.textBtnListener(baseConfigHeader, R.id.car_test_backCarRadar_tv, R.id.car_test_backCarRadar_bt,
                R.array.back_randar_strValue, configInfo.park_help, new ICheckValueListener() {

                    @Override
                    public void getValue(View v, String str) {
                        configInfo.park_help = str;
                    }
                });

        // 倒车影像
        CheckValueUtil.textBtnListener(baseConfigHeader, R.id.car_test_backCarImage_tv, R.id.car_test_backCarImage_bt,
                R.array.navigation_and_other_strValues, configInfo.reverse_view, new ICheckValueListener() {

                    @Override
                    public void getValue(View v, String str) {
                        configInfo.reverse_view = str;
                    }
                });

        // 中控液晶屏
        CheckValueUtil.textBtnListener(baseConfigHeader, R.id.base_center_LCD_tv, R.id.base_center_LCD_bt,
                R.array.have_entries, configInfo.centre_console_lcd, new ICheckValueListener() {

                    @Override
                    public void getValue(View v, String str) {
                        configInfo.centre_console_lcd = str;
                    }
                });

        // 可变悬架
        CheckValueUtil.textBtnListener(baseConfigHeader, R.id.base_can_change_suspension_tv,
                R.id.base_can_change_suspension_bt, R.array.have_entries, configInfo.variable_suspension,
                new ICheckValueListener() {

                    @Override
                    public void getValue(View v, String str) {
                        configInfo.variable_suspension = str;
                    }
                });

        // 随车工具
        CheckValueUtil.textBtnListener(baseConfigHeader, R.id.car_test_carTools_tv, R.id.car_test_carTools_bt,
                R.array.car_tools_strValues, configInfo.tool, new ICheckValueListener() {

                    @Override
                    public void getValue(View v, String str) {
                        configInfo.tool = str;
                    }
                });

        // 轮毂材质
        CheckValueUtil.textBtnListener(baseConfigHeader, R.id.car_test_hubMaterial_tv, R.id.car_test_hubMaterial_bt,
                R.array.hub_material_strValues, configInfo.hub_material, new ICheckValueListener() {

                    @Override
                    public void getValue(View v, String str) {
                        configInfo.hub_material = str;
                    }
                });

        // 前轮胎规格
        CheckValueUtil.textEditListener(baseConfigHeader, R.id.car_test_frontTiresNorms_tv,
                R.id.car_test_frontTiresNorms_et, configInfo.front_tire_size, new ICheckValueListener() {

                    @Override
                    public void getValue(View v, String str) {
                        configInfo.front_tire_size = str;
                    }
                });

        // 后轮胎规格
        CheckValueUtil.textEditListener(baseConfigHeader, R.id.car_test_behindTiresNorms_tv,
                R.id.car_test_behindTiresNorms_et, configInfo.rear_tire_size, new ICheckValueListener() {

                    @Override
                    public void getValue(View v, String str) {
                        configInfo.rear_tire_size = str;
                    }
                });

        // 备胎
        CheckValueUtil.textBtnListener(baseConfigHeader, R.id.car_test_spareTire_tv, R.id.car_test_spareTire_bt,
                R.array.have_entries, configInfo.spare_tire, new ICheckValueListener() {

                    @Override
                    public void getValue(View v, String str) {
                        configInfo.spare_tire = str;
                    }
                });

        // 加装项目
        CheckValueUtil.textEditListener(baseConfigHeader, R.id.car_test_retroitems_tv,
                R.id.car_test_retroitems_et, configInfo.retro_items, new ICheckValueListener() {

                    @Override
                    public void getValue(View v, String str) {
                        configInfo.retro_items = str;
                    }
                });
    }


    private void checkVIN(final String vin) {

        if (firstCheckVin) {
            firstCheckVin = false;
            return;
        }


        Map<String, String> params = new HashMap<String, String>();
        params.put("vin", vin);

        Request req = HttpRequest.getRequest(HttpRequest.POST, Api.Action.VIN_CHECK, params,
                new Response.Listener<JsonObject>() {
                    @Override
                    public void onResponse(JsonObject response) {
                        isOKVin = true;
                        condition.config_info.vin = vin;
                        getCarMsgByVin(vin);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        isOKVin = false;
                        T.showShort(mContext, error.getMessage());
                    }
                });
        VolleyUtil.getInstance().getRequestQueue().add(req);
    }

    @Override
    public void initDataAfterView() {

//        if (vinCarInfor!=null){
//            System.out.println("ws---vincarinfo开始赋值了");
//            setCarInfoFromVin(vinCarInfor);
//        }else{
//            System.out.println("ws---vincarinfo开始null");
//        }

    }

    @Override
    public void initDataBeforView() {
//        if (GlobalInfo.draft == null) {
//            GlobalInfo.draft = new Draft();
//        }
        condition = GlobalInfo.draft.condition.clone();

    }

    @Override
    public void initListener() {

    }

    /**
     * 配置检测数据
     *
     * @return
     */
    private ArrayList<Detection> getFunctionCheckData() {
        ArrayList<Detection> array = new ArrayList<Detection>();

//        String header = mContext.getString(R.string.base_config_check_subtitle);
//        // String[] values =
//        // GlobalInfo.resources.getStringArray(R.array.funciton_two_select_values);
//        // Detection detection = null;
//        String[] texts = GlobalInfo.resources.getStringArray(R.array.config_check_strKey_entries);
//
//        int i = 0;
//        array.add(getFunctionCheckItem(header, texts[i++], condition.function_check.abs_light));
//        array.add(getFunctionCheckItem(header, texts[i++], condition.function_check.airbag_light));
//        array.add(getFunctionCheckItem(header, texts[i++], condition.function_check.engine_light));
//        array.add(getFunctionCheckItem(header, texts[i++], condition.function_check.brake_light));
//        array.add(getFunctionCheckItem(header, texts[i++], condition.function_check.machine_light));
//        array.add(getFunctionCheckItem(header, texts[i++], condition.function_check.tachometer));
//        array.add(getFunctionCheckItem(header, texts[i++], condition.function_check.navigation));
//        // 空调（出风温度）
//        array.add(getFunctionCheckItem(header, texts[i++], condition.function_check.air_min_temperature));
//
//        //倒车雷达
//        array.add(getFunctionCheckItem(header, texts[i++], condition.function_check.park_help));
////        array.add(getFunctionCheckItemThree(header, texts[i++], condition.function_check.park_help));
//
//        array.add(getFunctionCheckItem(header, texts[i++], condition.function_check.reverse_view));
//        array.add(getFunctionCheckItem(header, texts[i++], condition.function_check.dvd));
//        array.add(getFunctionCheckItem(header, texts[i++], condition.function_check.horn));
//        array.add(getFunctionCheckItem(header, texts[i++], condition.function_check.rain_stroke));
//        array.add(getFunctionCheckItem(header, texts[i++], condition.function_check.motor_chair));
//        array.add(getFunctionCheckItem(header, texts[i++], condition.function_check.motor_mirror));
//        array.add(getFunctionCheckItem(header, texts[i++], condition.function_check.centre_console_lcd));
//        array.add(getFunctionCheckItem(header, texts[i++], condition.function_check.variable_suspension));
        return array;
    }

    private Detection getFunctionCheckItemThree(String header, String text, int value) {
        Detection detection = new Detection(Detection.TYPE_THREE_SELECT);
        detection.setHeader(header);
        detection.setRequestFocus(true);
        detection.setResId(R.array.funciton_three_select_values);
        detection.setValue(value);
        detection.setText(text);
        return detection;
    }

//    private Detection getFunctionCheckItemRefrigeration(String header, String text, boolean value) {
//        Detection detection = new Detection(Detection.TYPE_TWO_SELECT);
//        detection.setHeader(header);
//        detection.setRequestFocus(true);
//        detection.setResId(R.array.funciton_two_select_values_refrigeration);
//        detection.setValue(value ? 1 : 0);
//        detection.setText(text);
//        return detection;
//    }

    private Detection getFunctionCheckItem(String header, String text, int value) {
        Detection detection = new Detection(Detection.TYPE_THREE_SELECT);
        detection.setHeader(header);
        detection.setRequestFocus(true);
        detection.setResId(R.array.funciton_three_select_values);
        detection.setValue(value);
        detection.setText(text);
        return detection;
    }

//    public void onActivityResultView(int requestCode, int resultCode, Intent data) {
//        if (resultCode == Activity.RESULT_OK) {
//            switch (requestCode) {
//                case FORM_PAINT:// 漆膜厚度
//                    ArrayList<PaintThickness> paintThickness = (ArrayList<PaintThickness>) data
//                            .getSerializableExtra("PaintThickness");
//                    // paintThicknessAdapter.setData(paintThickness);
//                    condition.paint_thickness = paintThickness.toArray(new PaintThickness[0]);
//                    paintThicknessAdapter.setData(condition.paint_thickness);
//                    // 创建主视图
//                    CoverImageUtil.createPaintCoverView(condition.paint_thickness,
//                            (ImageView)findViewById(R.id.coverView));
//                    L.i("paintThickness = " + toJson(paintThickness));
//                    // for (int i = 0; i < paintThicknessAdapter.getCount(); i++)
//                    // L.i(toJson(paintThicknessAdapter.getItem(i)));
//                    break;
//
//            }
//        }
//    }

//
//    @Override
//    public void onSuccess(final VinCarInfor[] data) {
//
//        ((Activity) mContext).runOnUiThread(new Runnable() {
//            public void run() {
//                // 没有相应的车型信息
//                if (data == null || data.length == 0) {
//                    ToastUtil.showToastLong(R.string.get_vin_message_no);
//                    return;
//                }
//
//                // 只有唯一数据
//                if (data.length == 1) {
//                    setCarInfoFromVin(data[0]);
//                    return;
//                }
//
//                // 当有多个车辆信息时，让用户选择
//
//                // 车辆信息标题
//                String[] carInfoLabels = new String[data.length];
//                for (int i = 0; i < data.length; i++)
//                    carInfoLabels[i] = data[i].brand_caption;
//
//                // 显示选择对话框
//                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
//
//                builder.setTitle(R.string.get_vin_message_dialog_title)
//                        .setItems(carInfoLabels, new DialogInterface.OnClickListener() {
//
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                setCarInfoFromVin(data[which]);
//                            }
//                        }).show();
//            }
//        });
//
//    }
//
//    @Override
//    public void onFail() {
//        // 显示选择对话框
//        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
//
//        builder.setTitle(R.string.prompt).setMessage(R.string.get_vin_message_no)
//                .setPositiveButton(R.string.ok, null).show();
//    }

//    public void setCarInfoFromVin() {
//        setCarInfoFromVin(vinCarInfor);
//    }

    /**
     * 通过Vin设置车辆信息
     *
     * @param vinCarInfo
     */
    public void updateCarInfoFromVIN(VinCarInfor vinCarInfo) {
        if (vinCarInfor == null) {
            return;
        }

        // 排量
        setValueFromVinCarInfo(R.id.base_displace_et, vinCarInfo.displacement);

        // ABS
        setValueFromVinCarInfo(R.id.car_test_ABS_bt, vinCarInfo.abs_caption);

        // 气囊数
        setValueFromVinCarInfo(R.id.car_test_airbagCount_et, vinCarInfo.airbag);

        // 真皮座椅
        setValueFromVinCarInfo(R.id.car_test_leatherSeat_bt, vinCarInfo.leather_seats_caption);

        // 电动门窗
        setValueFromVinCarInfo(R.id.car_test_eCarWindow_bt, vinCarInfo.electrically_window_caption);

        // 天窗
        setValueFromVinCarInfo(R.id.car_test_skyWindow_bt, vinCarInfo.window_caption);

        // 导航
        setValueFromVinCarInfo(R.id.car_test_navigation_bt, vinCarInfo.gps_navigator_caption);

        // 转向助力
        setValueFromVinCarInfo(R.id.car_test_turnAroundPower_bt, vinCarInfo.booster_type_caption);

        // 电动座椅
        setValueFromVinCarInfo(R.id.car_test_eSeat_bt, vinCarInfo.electrically_seat_caption);

        // 空调
        setValueFromVinCarInfo(R.id.car_test_airConditioner_bt, vinCarInfo.air_caption);

        // 音响 赋空值
        setValueFromVinCarInfo(R.id.base_sount_sys_bt, "");

        // 定速巡航
        setValueFromVinCarInfo(R.id.car_test_automaticCruise_bt, vinCarInfo.auto_adapt_drive_caption);

        // 电动反光镜
        setValueFromVinCarInfo(R.id.car_test_eReflector_bt, vinCarInfo.back_mirror_electrically_caption);

        // 智能钥匙 赋空值
        setValueFromVinCarInfo(R.id.base_smart_key_bt, "");

        // DVD
        setValueFromVinCarInfo(R.id.car_test_DVD_bt, vinCarInfo.dvd_caption);

        // 倒车雷达
        setValueFromVinCarInfo(R.id.car_test_backCarRadar_bt, vinCarInfo.park_help_caption);

        // 倒车影像
        setValueFromVinCarInfo(R.id.car_test_backCarImage_bt, vinCarInfo.reverse_view_caption);

//        // 中控液晶屏 赋空值
//        setValueFromVinCarInfo(R.id.base_center_LCD_bt, "");

////         可变悬架 赋空值
//        setValueFromVinCarInfo(R.id.base_can_change_suspension_bt, "");

//        // 随车工具 赋空值
//        setValueFromVinCarInfo(R.id.car_test_carTools_bt, "");

        // 轮毂材质
        setValueFromVinCarInfo(R.id.car_test_hubMaterial_bt, vinCarInfo.hub_material_caption);

        // 前轮胎规格
        setValueFromVinCarInfo(R.id.car_test_frontTiresNorms_et, vinCarInfo.front_tire_size);

        // 后轮胎规格
        setValueFromVinCarInfo(R.id.car_test_behindTiresNorms_et, vinCarInfo.rear_tire_size);

        // 备胎
        setValueFromVinCarInfo(R.id.car_test_spareTire_bt, vinCarInfo.spare_tire_caption);

    }

    /**
     * 用VIN得到的车辆信息来设值
     *
     * @param resId
     * @param text
     */
    private void setValueFromVinCarInfo(int resId, String text) {
        L.i("text = " + text);
        if (!TextUtils.isEmpty(text)) {
            ((TextView) findViewById(resId)).setText(text);
        }
    }

    @Override
    public void onResult(int position, String value) {
//        condition.function_check.air_min_temperature = value;
    }

    @Override
    public void onResult(int position, int value) {
        boolean booleanValue = value == 0 ? false : true;
        switch (position) {
            case 0:
                condition.function_check.abs_light = value;
                break;
            case 1:
                condition.function_check.airbag_light = value;
                break;
            case 2:
                condition.function_check.engine_light = value;
                break;
            case 3:
                condition.function_check.brake_light = value;
                break;
            case 4:
                condition.function_check.machine_light = value;
                break;
            case 5:
                condition.function_check.tachometer = value;
                break;
            case 6:
                condition.function_check.navigation = value;
                break;
            case 7:
                condition.function_check.air_min_temperature = value;
                break;
            case 8:
//                condition.function_check.park_help = value;
                condition.function_check.park_help = value;
                break;
            case 9:
                condition.function_check.reverse_view = value;
                break;
            case 10:
                condition.function_check.dvd = value;
                break;
            case 11:
                condition.function_check.horn = value;
                break;
            case 12:
                condition.function_check.rain_stroke = value;
                break;
            case 13:
                condition.function_check.motor_chair = value;
                break;
            case 14:
                condition.function_check.motor_mirror = value;
                break;
            case 15:
                condition.function_check.centre_console_lcd = value;
                break;
            case 16:
                condition.function_check.variable_suspension = value;
                break;

        }

    }

    public void onResult(int position, ArrayList<Integer> value) {

    }

    /**
     * 启动选项
     *
     * @param requestCode
     */
    private void startIndexSelectActivityForResult(int requestCode, Intent intent) {
//        switch (requestCode) {
//            case REQUEST_CAR_BRAND:
//                intent.setClass(mContext, CarActivity.class);
//                break;
//            case REQUEST_CAR_SERIES:
//                intent.setClass(mContext, CarActivity.class);
//                break;
//            case REQUEST_CAR_MODEL:
//                intent.setClass(mContext, CarActivity.class);
//                break;
//        }
//        ((Activity) mContext).startActivityForResult(intent, requestCode);
    }

    public void onActivityResultView(int requestCode, int resultCode, Intent data) {
        System.out.println("ws----view中" + "requestCode = " + requestCode + " resultCode = " + resultCode);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CAR_BRAND:// 品牌
                case REQUEST_CAR_MODEL:
                case REQUEST_CAR_SERIES:
                    //保存品牌
                    CarEntity carEntity = (CarEntity) data.getSerializableExtra(CarActivity.EXTRA_DATA);
                    condition.config_info.brand_id = carEntity.getbId();
                    condition.config_info.brand_str = carEntity.getbName();
//                    Button base_car_brand_bt = (Button) findViewById(R.id.base_car_brand_bt);
//                    base_car_brand_bt.setText(carEntity.getbName());
//
//                    //保存车系
                    condition.config_info.series_id = carEntity.getsId();
                    condition.config_info.series_str = carEntity.getsName();

//                    ((Button) findViewById(R.id.base_car_series_bt))
//                            .setText(carEntity.getsName());
//
//                    // 保存车型
                    condition.config_info.model_id = carEntity.getmId();
                    condition.config_info.model_str = carEntity.getmName();

                    ((Button) findViewById(R.id.base_car_brand_bt)).setText(carEntity.getbName() + " " + carEntity.getsName() + " " + carEntity.getmName());
                    break;
            }
        }
    }

    /**
     * 通过VIN获取车辆信息
     */
    private void getCarMsgByVin(String vin) {
        Map<String, String> params = new HashMap<String, String>();
        String url = CarDbUtil.getUrl(Api.Action.CAR_BY_VIN, "&vin=" + vin);

        Request req = new VinCarRequest(params, url,
                new Response.Listener<VinCarInfor[]>() {
                    @Override
                    public void onResponse(final VinCarInfor[] data) {

                        // 没有相应的车型信息
                        if (data == null || data.length == 0) {
//                            ToastUtil.showToastLong(R.string.get_vin_message_no);
                            return;
                        }

                        // 只有唯一数据
                        if (data.length == 1) {
                            setCarInfoFromVin(data[0]);
                            return;
                        }

                        // 当有多个车辆信息时，让用户选择

                        // 车辆信息标题
                        String[] carInfoLabels = new String[data.length];
                        for (int i = 0; i < data.length; i++)
                            carInfoLabels[i] = data[i].brand_caption;

                        // 显示选择对话框
                        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);

                        builder.setTitle(R.string.get_vin_message_dialog_title)
                                .setItems(carInfoLabels, new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        setCarInfoFromVin(data[which]);
                                    }
                                }).show();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                setCarInfoFromVin(null);
            }
        });
        VolleyUtil.getInstance().getRequestQueue().add(req);
    }

    /**
     * 通过Vin设置车辆信息
     *
     * @param vinCarInfo
     */
    private void setCarInfoFromVin(VinCarInfor vinCarInfo) {
        if (vinCarInfo != null) {
            this.vinCarInfor = vinCarInfo;
//            intent.putExtra(MainActivity.VINCARINFOR, vinCarInfo);
            //车型车系信息
            GlobalInfo.draft.condition.config_info.brand_id = Integer.parseInt(vinCarInfo.brand_id);
            GlobalInfo.draft.condition.config_info.series_id = Integer.parseInt(vinCarInfo.series_id);
            GlobalInfo.draft.condition.config_info.model_id = Integer.parseInt(vinCarInfo.model_id);
            GlobalInfo.draft.condition.config_info.brand_str = vinCarInfo.brand_caption;
            GlobalInfo.draft.condition.config_info.model_str = "";
            GlobalInfo.draft.condition.config_info.series_str = "";

            //配置功能信息
            GlobalInfo.draft.condition.config_info.abs = vinCarInfo.abs;
            GlobalInfo.draft.condition.config_info.airbag = vinCarInfo.airbag;
            GlobalInfo.draft.condition.config_info.leather_seats = vinCarInfo.leather_seats_caption;
            GlobalInfo.draft.condition.config_info.electrically_window = vinCarInfo.electrically_window_caption;
            GlobalInfo.draft.condition.config_info.window = vinCarInfo.window_caption;
            GlobalInfo.draft.condition.config_info.gps_navigator = vinCarInfo.gps_navigator_caption;
            GlobalInfo.draft.condition.config_info.booster_type = vinCarInfo.booster_type_caption;
            GlobalInfo.draft.condition.config_info.electrically_seat = vinCarInfo.electrically_seat_caption;
            GlobalInfo.draft.condition.config_info.air = vinCarInfo.air_caption;
            GlobalInfo.draft.condition.config_info.auto_adapt_drive = vinCarInfo.auto_adapt_drive_caption;
            GlobalInfo.draft.condition.config_info.back_mirror_electrically = vinCarInfo.back_mirror_electrically_caption;
            GlobalInfo.draft.condition.config_info.dvd = vinCarInfo.dvd_caption;
            GlobalInfo.draft.condition.config_info.park_help = vinCarInfo.park_help_caption;
            GlobalInfo.draft.condition.config_info.reverse_view = vinCarInfo.reverse_view_caption;
            GlobalInfo.draft.condition.config_info.hub_material = vinCarInfo.hub_material_caption;
            GlobalInfo.draft.condition.config_info.front_tire_size = vinCarInfo.front_tire_size;
            GlobalInfo.draft.condition.config_info.rear_tire_size = vinCarInfo.rear_tire_size;
            GlobalInfo.draft.condition.config_info.spare_tire = vinCarInfo.spare_tire_caption;

            saveVinCarInfoDb();
        }
    }

    //更新数据库，立即保存通过vin码获取到的车辆信息
    private void saveVinCarInfoDb() {

        ContentValues values = new ContentValues();

        //保存车型车系信息
        BaseInfo baseInfo = GlobalInfo.draft.base_info;
        values.put(DbHelper.KEY_DRAFT_BASE_INFO, toJson(baseInfo));
        int status_base = baseInfo.getStatus();
        values.put(DbHelper.KEY_DRAFT_BASE_INFO_STATUS, status_base);

        //保存配置信息
        Condition condition = GlobalInfo.draft.condition;
        values.put(DbHelper.KEY_DRAFT_CONDITION, toJson(GlobalInfo.draft.condition));
        int status = condition.getStatus();
        values.put(DbHelper.KEY_DRAFT_CONDITION_STATUS, status);



        // 保存成功
        if (GlobalInfo.dbHelper.updateDraf(GlobalInfo.tempOwner, values)) {
            GlobalInfo.draft.base_info = baseInfo.clone();
            GlobalInfo.draft.status[Draft.TYPE_BASE_INFO] = status;

            GlobalInfo.draft.condition = condition.clone();
            GlobalInfo.draft.car_vin = condition.config_info.vin;
            GlobalInfo.draft.status[Draft.TYPE_CONDITION] = status;
            L.i(toJson(GlobalInfo.draft.condition));

            updateCarInfoFromVIN(vinCarInfor);
        }
    }
}
